package middlewares

import (
	"context"
	"gin-study/app/services"
	"gin-study/config"
	"gin-study/pkg/helper"
	"github.com/gin-gonic/gin"
	"github.com/opentracing/opentracing-go"
	"github.com/opentracing/opentracing-go/ext"
)

func init() {
}

func Trace() gin.HandlerFunc {
	return helper.WarpHandle(func(c *gin.Context) interface{} {
		span, ctx := startSpanFromRequest(c)
		defer span.Finish()
		services.Ctx.SetTraceCtx(c, ctx)
		c.Next()
		return nil
	})

}

//从请求中创建上下文
func startSpanFromRequest(c *gin.Context) (span opentracing.Span, ctx context.Context) {
	tracer := opentracing.GlobalTracer()
	//从请求中拦截上下文
	spanCtx, err := tracer.Extract(opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(c.Request.Header))

	spanName := config.App.Name

	if err != nil {
		span, ctx = opentracing.StartSpanFromContext(context.Background(), spanName)
	} else {
		span, ctx = opentracing.StartSpanFromContext(context.Background(), spanName, opentracing.ChildOf(spanCtx))
	}

	ext.HTTPStatusCode.Set(span, uint16(c.Writer.Status()))
	ext.HTTPUrl.Set(span, c.Request.URL.Path)
	ext.HTTPMethod.Set(span, c.Request.Method)

	return
}
